package com.cema.manage.common.utils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 获取IP方法
 *
 * @author reasahi
 */
public class IpUtils {
    public static String getIpAddr(HttpServletRequest request) {
        if (request == null) {
            return "unknown";
        }
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }

    private static long ipToLong(InetAddress ip) {
        // 获取IP的字节数组
        byte[] octets = ip.getAddress();
        long result = 0;
        for (byte octet : octets) {
            // 逐字节左移并与掩码相与
            result = (result << 8) | (octet & 0xFF);
        }
        return result;
    }

    /**
     * 网段记录值 &运算Long类型
     *
     * @param ip1
     * @return
     * @throws UnknownHostException
     */
    public static long getInSameNetwork(String ip1) throws UnknownHostException {
        InetAddress addr1 = InetAddress.getByName(ip1);
        String subnetMask = getSubnetMask(ip1);
        InetAddress mask = InetAddress.getByName(subnetMask);
        // 将第一个IP转换为长整型
        long addr1Long = ipToLong(addr1);
        // 将第二个IP转换为长整型
        //long addr2Long = ipToLong(addr2);
        // 将网络掩码转换为长整型
        long maskLong = ipToLong(mask);

        // 通过按位与比较IP地址
        return (addr1Long & maskLong);
    }


    private static String getSubnetMask(String ipAddress) {
//        String[] parts = ipAddress.split("\\.");
//        int firstOctet = Integer.parseInt(parts[0]);
//        if (firstOctet <= 127) {
//            // A类
//            return "255.0.0.0";
//        } else if (firstOctet <= 191) {
//            // B类
//            return "255.255.0.0";
//        } else {
            // C类
            return "255.255.255.0";
//        }
    }
}
